// pages/writePage/writePage.js
const event = require('../../tqlsdk/event')
const tqlSDK = getApp().globalData.tqlSDK
const ctx = wx.createCanvasContext('canvas');
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog"
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast"
const mapOnline = new Map()
const mapOffline = new Map();
const b5_width = 182.86; //b5纸的宽度
const b5_height = 256; //b5纸的高度
const x_codepoint_size = 1.524; //横坐标码点的大小
const y_codepoint_size = 1.524; //纵坐标码点的大小
const ax = b5_width / x_codepoint_size;
const ay = b5_height / y_codepoint_size;
const color = "#000";
var force = 0;
var scale = 1;
var offsetX = 0;
var offsetY = 0.0;
var lineWidth = 2;
var penWidth = 1.0;
var x_coordinate = 0.0;
var y_coordinate = 0.0;
var isDown = false;
var p_index = -1;
var currentX = 0;
var currentY = 0; //当前点
var currentMidX = 0;
var currentMidY = 0; //当前中间点
var preMidX = 0;
var preMidY = 0; //上一个中间点
var preX = 0;
var preY = 0; //上一个点
var lastPointX = 0.0;
var lastPointY = 0.0;
var toast = null
let loadingOffline = false
let stampFlag = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cvsWidth: null,
    cvsHeight: null,
    lastPage: 1, //上一页
    images: ['../../pages/images/page1.png', "../../pages/images/page2.png"],
    imgUrl: null,
    isShowColor: false,
    isShowOfflineView: false,
    ctx: null,
    replay: false,
    isChangePage: false,
    loadingOfflineData: false,
    showPop: false,
    isReplay: false,
    isLoadingOffline: false,
    penName: "", //笔名
    offTime: null, //关机时间
    showInfoPage: false, //显示笔的信息修改页面
    offlineNum: 0, //离线数据总数据量
    offlineGross: 0, //离线数据进程
    showProgress: false, //是否显示进度条
    macAddress: '', //mac地址
    blueToothVerison: '', //蓝牙固件版本
    penBattery: '', //笔的电量
    penRTC: '', //rtc时间
    penAutoOff: '', //笔自动关机时间
    penMemory: '', //笔内容使用状况
    penClickMode: false, //比是否点笔开机
    penBeep: false, //蜂鸣器开关
    penSensor: '', //笔的压力值
    MCUversion: '', //mcu固件版本
    oldPenName: '', //老笔名
    changePenNameFlag: false, //修改笔名flag
    oldPenAuto: null, //老笔的自动关机时间
    oldSensor: null, //老线宽
    date: null, //日期
    time: null, //时间
    showSpeed: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (result) => {
        this.setData({
          cvsWidth: result.windowWidth,
          cvsHeight: result.windowHeight - 30
        })
      },
    })
    this.changePage(0);
    // 获取离线数据量
    this.getOfflineNum();
    // 监听获取数据
    event.on("AddressDataChanged", this, data => {
      if (data) {
        // console.log(data)
        this.dataRecieve(data)
      }
    })
    // event.on("offlineDataFinish", this, (data) => {

    // })
    event.on('finish', this, (data) => {
      this.setData({
        showProgress: false
      })
    })
    // 连接状态监听
    event.on('unConnect', this, (data) => {
      this.setData({
        loadingOffline: false
      })
      wx.showModal({
        title: '警告',
        content: '蓝牙断开',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            // event.emit('disconnect',data)
            this.setData({
              loadingOffline: false
            })
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    })
    // 监听事件
    event.on('penData', this, data => {
      switch (data.cmd) {
        // 获取离线数据量
        case "getOfflineDataNum":
          this.setData({
            offlineNum: data.data
          })

          break
          // 离线数据获取进程
        case "offLineProgress":
          let gross = Math.floor((data.data / this.data.offlineNum) * 100)
          if (this.data.offlineNum - data.data < 100) {
            this.setData({
              showProgress: false,
              loadingOffline: false
            })
            wx.showToast({
              title: '离线下载完成',
              icon: 'success',
              duration: 800,
              mask: true
            })
          }
          this.setData({
            offlineGross: gross
          })
          break
          // 停止获取离线数据
        case "offLineProgressStop":
          break
          // 确认离线数据全部接收完毕
        case "offLineDataConfirm":
          break
          // 删除离线数据
        case "offLineDataDelete":
          Dialog.close();
          this.setData({
            imgUrl: ''
          })
          break;
          // 监听笔名
        case "getPenName":
          if (this.data.changePenNameFlag) {
            Toast.success("修改成功")
          }
          this.setData({
            penName: data.data,
            changePenNameFlag: false,
            oldPenName: data.data
          })
          break;
        case 'setPenName':
          setTimeout(() => {
            Toast.clear()
            this.getPenName();
          }, 1500)
          break
          // 获取mac地址
        case "getMacAddress":
          this.setData({
            macAddress: data.data
          })
          break
        case "getBlueToothVersion":
          this.setData({
            blueToothVerison: data.data
          })
          break
        case 'getPenBattery': //获取笔的电量
          this.setData({
            penBattery: data.data.penBattery
          })
          break
        case 'getRTCtime': //获取笔的时间
          // console.log(data.data)
          let penTime = this.formatDate(data.data)
          let penTimeArray = penTime.split(" ");
          console.log(penTimeArray[1])
          let newtime = penTimeArray[1].split(":")
          newtime.pop();
          let res = newtime.join(":")
          this.setData({
            date: penTimeArray[0],
            time: res
          })
          break
        case "setRTCtime":
          setTimeout(() => {
            Toast.clear();
            Toast.success('修改成功')
          }, 1500)
          break
        case 'getPenAutoShutDownTime': //获取笔是否自动关机
          if (this.data.changePenNameFlag) {
            Toast.success("修改成功")
          }
          this.setData({
            changePenNameFlag: false,
            penAutoOff: data.data
          })
          break
        case "setPenAutoOff": //设置笔的自动关机时间
          setTimeout(() => {
            Toast.clear()
            this.getPenAutoOff()
          }, 1500)
          break
        case "setPenClickMode":
          setTimeout(() => {
            Dialog.close();
            this.getPenClickMode();
          }, 1000)
          break
        case 'getUsedMemory': //获取笔的内存使用情况
          console.log('内存', data.data)
          this.setData({
            penMemory: data.data
          })
          break
        case 'getPenClickMode': //获取是否点笔开机
          this.setData({
            penClickMode: data.data
          })
          break
        case 'setPenBeep': //设置蜂鸣器是否开启
          setTimeout(() => {
            this.getPenBeep();
            Dialog.close()
          }, 1000)
          break
        case "getPenBeep":
          this.setData({
            penBeep: data.data
          })
          break
        case 'getPenSensor': //获取笔的压力值
          console.log(data.data)
          this.setData({
            penSensor: data.data
          })
          if (this.data.changePenNameFlag) {
            this.setData({
              changePenNameFlag: false
            })
            Toast.success("修改成功")
          }
          break
        case "setPenSensor":
          setTimeout(() => {
            Toast.clear();
            this.setData({
              changePenNameFlag: true
            })
            this.getPenSensor()
          }, 1500)
          break
        case 'getMCUVersion': //获取mcu固件版本
          this.setData({
            MCUversion: data.data
          })
          break;
          // 恢复出厂设置
        case "RestoreFactorySettings":
          // 获取笔名
          this.getPenName();
          // 获取mac地址
          this.getMACAddress();
          // 获取蓝牙固件版本
          this.getPenFirmWare();
          // 获取剩余电量
          this.getPenBattery();
          // 获取rtc时间
          this.getPenTime();
          // 获取自动关机时间
          this.getPenAutoOff();
          // 获取已使用内存
          this.getPenMemory();
          // 获取是否点笔开机
          this.getPenClickMode();
          // 获取蜂鸣器开关
          this.getPenBeep();
          // 获取压力敏感度
          this.getPenSensor();
          setTimeout(() => {
            Dialog.close()
          }, 2000)
          break;
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    event.remove('penData', this)
    event.remove('AddressDataChanged', this)
    event.remove('unConnect', this)
    event.remove('finish', this)
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    event.remove('penData', this)
    event.remove('AddressDataChanged', this)
    event.remove('unConnect', this)
    event.remove('finish', this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 修改页码
  changePage(index) {
    if (index === this.data.lastPage && !this.data.isReplay) {
      return
    }
    // console.log(!((this.data.lastPage ^ index) & 1))
    // if (!((this.data.lastPage ^ index) & 1)) {
    //   this.setData({

    //     lastPage: index
    //   })
    //   ctx.draw();
    //   return
    // }
    // if (this.data.lastPage !== index) {
    this.setData({
      lastPage: index
    })
    // }
    // console.log(this.data.images)
    ctx.drawImage(this.data.images[(index & 1) ? 1 : 0], 0, 0, this.data.cvsWidth, this.data.cvsHeight)
    ctx.draw();
  },
  // 接收数据
  dataRecieve(data) {
    if (this.data.replay) {
      wx.showToast({
        title: '正在回放',
        icon: 'loading',
        duration: 1000
      })
      return
    }
    if (this.data.isChangePage) {
      mapOnline.get(this.data.lastPage).push(data)
      return
    }
    this.getDrawData(data)
  },
  // 四舍五入算法
  roundNum(number, fractionDigits) {
    return Math.round(number * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits);
  },
  // 数据处理
  getDrawData(data) {
    // if (data) {
    //   data.pageID += 1
    // }
    if (data.dotType === 'PEN_DOWN') {
      //此处进行翻页操作
      this.addPageId(data.pageID, data)
    }
    // console.log(data,1111)
    force = data.force
    let xPoint = this.roundNum((((data.x + (data.fx / 100)) * this.data.cvsWidth) / ax), 13);
    let yPoint = this.roundNum((((data.y + (data.fy / 100)) * this.data.cvsHeight) / ay), 13);
    x_coordinate = data.x + (data.fx / 100);
    y_coordinate = data.y + (data.fy / 100);
    mapOnline.get(data.pageID).push({
      bookId: data.bookID,
      pageID: data.pageID,
      timeLong: data.timeLong,
      xPoint,
      yPoint,
      dotType: data.dotType,
      penWidth: this.setPenFront(data.force),
      force: data.force,
      color
    });
    this.penType(data.dotType, xPoint, yPoint, color)
  },
  //  点的类型
  penType(penType, x, y, color) {
    penType === "PEN_DOWN" ? this.penDown(x, y, color) : penType === "PEN_MOVE" ? this.penmove(x, y, color) : this.penup(x, y, color)
  },
  // 写字方法
  drawPen(scale, offsetX, offsetY, lineWidth, x_o, y_o, force) {
    if (p_index === 0) {
      currentMidX = preX = preMidX = currentX = x_o * scale + offsetX + 0.1
      currentMidY = preY = preMidY = currentY = y_o * scale + offsetY
      return
    }
    if (p_index > 1) {
      currentX = x_o * scale + offsetX + 0.1;
      currentY = y_o * scale + offsetY;
      currentMidX = (currentX + preX) / 2.0;
      currentMidY = (currentY + preY) / 2.0;
      ctx.beginPath();
      ctx.setLineCap('round');
      ctx.setLineJoin('miter');
      ctx.moveTo(preMidX, preMidY);
      ctx.lineWidth = 1;
      ctx.quadraticCurveTo(preX, preY, currentMidX, currentMidY);
      ctx.setStrokeStyle(color);
      ctx.fill();
      ctx.stroke();
      ctx.closePath();
      ctx.draw(true);
      if (force === 0) {
        ctx.moveTo(currentMidX, currentMidY);
        ctx.lineWidth = penWidth
        ctx.lineTo(currentX, currentY); // 终点
      }
      preMidX = currentMidX;
      preMidY = currentMidY;
      preX = currentX;
      preY = currentY; //使用完成后赋值等待下一个点进来。
    }
  },
  //  下笔方法
  penDown(x, y, color) {
    if (isDown) {
      this.drawPen(scale, offsetX, offsetY, lineWidth, preX, preY, 0);
      isDown = false;
    }
    p_index = 0;
    color = color
    this.drawPen(scale, offsetX, offsetY, lineWidth, x, y, force);
    if (this.data.isShowColor || this.data.isShowOfflineView) {
      this.setData({
        isShowColor: false,
        isShowOfflineView: false
      })
    }
    isDown = true
    lastPointX = x
    lastPointY = y
  },
  // 移动点
  penmove(x_o, y_o, color) {
    if (!isDown) {
      p_index = 0;
      isDown = true
      this.drawPen(scale, offsetX, offsetY, lineWidth, x_o, y_o, force)
      return
    }
    p_index += 1;
    this.drawPen(scale, offsetX, offsetY, lineWidth, x_o, y_o, force)
  },
  // up点
  penup(x_o, y_o, color) {
    isDown = false
    this.drawPen(scale, offsetX, offsetY, lineWidth, x_o, y_o, force)
  },
  // 划线
  drawLine(x1, y1, x2, y2, color) {
    ctx.beginPath();
    ctx.setLineCap('round');
    ctx.setLineJoin('miter');
    ctx.moveTo(x1, y1);
    ctx.lineWidth = penWidth;
    ctx.lineTo(x2, y2)
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    ctx.draw(true)
  },
  setPenFront(force) {
    let mForce = parseInt(force)
    return mForce < 50 ? 0.8 : mForce < 90 ? 1.0 : mForce < 120 ? 1.2 : mForce < 150 ? 1.6 : mForce < 190 ? 1.8 : mForce < 210 ? 1.9 : mForce < 330 ? 2.0 : mForce < 500 ? 2.2 : mForce < 650 ? 2.3 : mForce < 800 ? 2.4 : 2.8
  },
  // 设置书号
  addPageId(myPageId) {
    if (myPageId === this.data.lastPage) {
      !mapOnline.get(myPageId) && mapOnline.set(myPageId, [])
      return
    }
    this.changePage(myPageId);
    !mapOnline.has(myPageId) && mapOnline.set(myPageId, [])
    mapOnline.get(myPageId).forEach((item) => {
      penWidth = this.setPenFront(item.force)
      this.penType(item.dotType, item.xPoint, item.yPoint, item.color)
    })
  },
  // 开始获取离线数据
  startGetOfflineData() {
    tqlSDK.startGetOfflineData(() => {

    }, () => {

    })
  },
  // 获取离线数据量
  getOfflineNum() {
    tqlSDK.getPenOfflineDataSize(() => {

    }, () => {

    })
  },
  // 停止获得离线数据
  stopGetOfflineData() {
    tqlSDK.stopGetOfflineData()
  },
  // 暂停获得离线数据
  pauseOfflineData() {
    tqlSDK.pauseGetOfflineData()
  },
  // 确认离线数据接收完毕
  confirmOfflineDataDone() {
    tqlSDK.confirmOfflineDataDone()
  },
  // 请求笔名
  getPenName() {
    tqlSDK.getPenName()
  },
  // 获取MAC地址
  getMACAddress() {
    tqlSDK.getMACAddress()
  },
  // 获取蓝牙固件版本
  getPenFirmWare() {
    tqlSDK.getPenFirmWare()
  },
  // 获取剩余电量
  getPenBattery() {
    tqlSDK.getPenBattery()
  },
  setPenTime(timeStamp) {
    tqlSDK.setRTCTime(timeStamp)
  },
  //  请求rtc时间
  getPenTime() {
    tqlSDK.getRTCTime()
  },
  // 写入自动关机时间
  setPenAutoOff(time) {
    tqlSDK.setPenAutoOff(time)
  },
  // 获取自动关机时间
  getPenAutoOff() {
    tqlSDK.getPenAutoOff()
  },
  // 获取已使用内存
  getPenMemory() {

    tqlSDK.getPenMemory()
  },
  // 获取是否点笔开机
  getPenClickMode() {
    tqlSDK.getPenClickMode()
  },
  // 设置点笔开机
  setPenClickMode(flag, f1, f2) {
    tqlSDK.setPenClickMode(flag, f1, f2)
  },
  // 获取是否蜂鸣
  getPenBeep() {
    tqlSDK.getPenBeep()
  },
  // 设置是否蜂鸣
  setPenBeep(flag) {
    tqlSDK.setPenBeep(flag)
  },
  // 恢复出厂设置
  restoreFactory() {
    tqlSDK.restoreFactory()
  },
  // 写入压力敏感值
  setPenSensor(sensor) {
    tqlSDK.setPenSensor(sensor)
  },
  // 获取压力敏感度
  getPenSensor() {
    tqlSDK.getPenSensor()
  },
  // 设置led灯颜色
  setPenLedColor() {
    tqlSDK.setPenLedColor()
  },
  // 获取led灯颜色
  getPenLedColor() {
    tqlSDK.getPenLedColor()
  },
  // 获取压力校正值
  getPenSensorRegulate() {
    tqlSDK.getPenSensorRegulate()
  },
  // 获取MCU固件版本
  getMCUVersion() {
    tqlSDK.getMCUVersion()
  },
  //获取笔的类型
  getPenModal() {
    tqlSDK.getPenModal()
  },
  // 获取led是否能够设置
  getLedConfig() {
    tqlSDK.getLedConfig()
  },
  // led设置开关
  setLedConfig() {
    tqlSDK.setLedConfig()
  },
  // 设置笔名
  setPenName(penName) {
    tqlSDK.setPenName(penName)
  },
  // 展示侧边栏
  showMenu() {
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: (res) => {
        console.log(res.tempFilePath)
        this.setData({
          imgUrl: res.tempFilePath,
          showPop: true
        })
      },
      fail: (res) => {
        console.log(res)
      }
    })
    this.setData({
      showPop: true
    })
  },
  // 恢复出厂设置
  restore() {
    tqlSDK.restoreFactory()
  },
  // 关闭侧边栏
  closePop() {
    this.setData({
      imgUrl: '',
      showPop: false
    })
  },
  // 展示笔的信息页
  showPenInfo() {
    this.setData({
      showPop: false,
      showInfoPage: true
    })
    // 获取笔名
    this.getPenName();
    // 获取mac地址
    this.getMACAddress();
    // 获取蓝牙固件版本
    this.getPenFirmWare();
    // 获取剩余电量
    this.getPenBattery();
    // 获取rtc时间
    this.getPenTime();
    // 获取自动关机时间
    this.getPenAutoOff();
    // 获取已使用内存
    this.getPenMemory();
    // 获取是否点笔开机
    this.getPenClickMode();
    // 获取蜂鸣器开关
    this.getPenBeep();
    // 获取压力敏感度
    this.getPenSensor();
    // 获取离线数据量
    this.getOfflineNum();
  },
  // 回放
  replay() {
    this.setData({
      isReplay: true
    })
    this.closePop()
    setTimeout(() => {
      // for (let value of mapOnline.keys()) {
      //   this.changePage(value);
      //   mapOnline.get(value).forEach( (item) => {
      //     penWidth = this.setPenFront(item.force);
      //     this.penType(item.dotType, item.xPoint, item.yPoint, item.color)
      //   })
      // }
      // this.setData({
      //   isReplay: false
      // })
      this.setData({
        isReplay: true
      })
      this.changePage(this.data.lastPage)
      if (mapOnline.get(this.data.lastPage)) {
        mapOnline.get(this.data.lastPage).forEach(item => {
          penWidth = this.setPenFront(item.force);
          this.penType(item.dotType, item.xPoint, item.yPoint, item.color)
        })
      }
      this.setData({
        isReplay: false
      })
    }, 1000)
  },
  // 查看离线数据
  getOfflineData() {
    this.setData({
      showPop: false
    })
    loadingOffline = true
    if (this.data.offlineNum === 0) {
      // Toast.fail('暂无离线数据')
      wx.showModal({
        title: '提示',
        content: '暂无离线数据',
        showCancel: false,
        success: () => {
          this.setData({
            imgUrl: ""
          })
        }
      })
      loadingOffline = false
      return
    }

    if (loadingOffline) {
      this.setData({
        imgUrl: '',
        showProgress: true
      })
      this.startGetOfflineData();
    }
    // this.getOfflineNum();
  },
  // 清空
  clear() {
    this.setData({
      showPop: false
    })
    Dialog.confirm({
      title: '警告',
      message: "清空后数据无法恢复",
      asyncClose: true
    }).then(() => {
      mapOnline.clear();
      ctx.drawImage(this.data.images[(this.data.lastPage & 1) ? 0 : 1], 0, 0, this.data.cvsWidth, this.data.cvsHeight);
      ctx.draw();
      setTimeout(() => {
        this.setData({
          imgUrl: ''
        })
        Dialog.close()
      }, 1000)
    }).catch(() => {
      this.setData({
        imgUrl: ""
      })
      Dialog.close()
    })
  },
  deleteOfflineData() {
    this.setData({
      showPop: false
    })
    Dialog.confirm({
      title: '警告',
      message: "离线数据清空后无法恢复",
      asyncClose: true
    }).then(() => {
      tqlSDK.deleteOfflineData();
    }).catch(() => {
      this.setData({
        imgUrl: ''
      });
      Dialog.close();
    })
  },
  // 点笔开机转换
  switchClick() {
    Dialog.confirm({
      title: "提示",
      message: "确认修改笔的点笔开机状态",
      asyncClose: true
    }).then(() => {
      this.setPenClickMode(!this.data.penClickMode)
    }).catch(
      () => {
        Dialog.close()
      }
    )
  },
  // 笔的蜂鸣器开关转换 
  switchBeep() {
    Dialog.confirm({
      title: '提示',
      message: "确认修改笔的蜂鸣器",
      asyncClose: true
    }).then(() => {
      this.setPenBeep(!this.data.penBeep)
    }).catch(() => {
      Dialog.close()
    })
  },
  getBackCanvas() {
    this.setData({
      showInfoPage: false,
      imgUrl: ''
    })
    this.setData({
      isReplay: true
    })
    this.changePage(this.data.lastPage)
    if (mapOnline.get(this.data.lastPage)) {
      mapOnline.get(this.data.lastPage).forEach(item => {
        penWidth = this.setPenFront(item.force);
        this.penType(item.dotType, item.xPoint, item.yPoint, item.color)
      })
    }
    this.setData({
      isReplay: false
    })
  },
  // 储存笔名
  savePenName() {
    this.setData({
      oldPenName: this.data.penName
    })
  },
  //修改笔名
  penNameChange() {
    if (!this.data.penName.trim()) {
      wx.showModal({
        title: '提示',
        content: '笔名不能为空',
        showCancel: false,
        success: () => {

        }
      })
      return
    }
    if (this.data.oldPenName.trim() === this.data.penName.trim()) {
      wx.showModal({
        title: '提示',
        content: '笔名未做修改',
        showCancel: false,
        success: () => {}
      })
      return
    }
    this.setData({
      changePenNameFlag: true
    })
    Toast.loading({
      message: '正在修改...',
      forbidClick: true,
    });
    this.setPenName(this.data.penName);
  },
  // 修改笔的自动关机时间
  changeAutoOff() {
    if (!this.data.penAutoOff) {
      wx.showModal({
        title: '提示',
        content: '时间不能为空',
        showCancel: false,
        success: () => {

        }
      })
    }
    if (this.data.penAutoOff === this.data.oldPenAuto) {
      wx.showModal({
        title: '提示',
        content: '时间未做修改',
        showCancel: false,
        success: () => {

        }
      })
      return
    }
    this.setData({
      changePenNameFlag: true
    })
    Toast.loading({
      message: '正在修改...',
      forbidClick: true,
    });
    this.setPenAutoOff(this.data.penAutoOff)
  },
  //笔的自动关机时间上限
  changeValue() {
    if (stampFlag) {
      clearTimeout(stampFlag)
    }
    // console.log(this.data.penAutoOff)
    stampFlag = setTimeout(() => {
      if (this.data.penAutoOff > 120) {
        this.setData({
          penAutoOff: 120
        })
      }
    }, 100)
  },
  // 存储笔的就关机时间
  saveOff() {
    this.setData({
      oldPenAuto: this.data.penAutoOff
    })
  },
  // 笔名回复
  recover() {
    if (this.data.penName.trim() === '') {
      this.setData({
        penName: this.data.oldPenName
      })
    }
  },
  // 自动关机时间回复
  recoverNum() {
    if (!this.data.penAutoOff && this.data.penAutoOff !== 0) {
      this.setData({
        penAutoOff: this.data.oldPenAuto
      })
    }
  },
  // 恢复出厂设置
  resetAll() {
    Dialog.confirm({
      title: "警告",
      message: '确定要恢复出厂设置？',
      asyncClose: true
    }).then(
      () => {
        this.restore()
      }
    ).catch(() => {
      Dialog.close()
    })
  },
  // 输入框压力值
  inputSensor() {
    if (!this.data.penSensor) {
      wx.showModal({
        title: '提示',
        content: '线宽不能为空',
        showCancel: false,
        success: () => {

        }
      })
    }
    if (this.data.penSensor === this.data.oldSensor) {
      wx.showModal({
        title: '提示',
        content: '线宽未做修改',
        showCancel: false,
        success: () => {}
      })
      return
    }
    this.setData({
      changePenNameFlag: true
    })
    // console.log(this.data.penSensor)
    Toast.loading({
      message: '正在修改...',
      forbidClick: true,
    })
    this.setPenSensor(this.data.penSensor)
  },
  // 保存线宽
  saveSensor() {
    this.setData({
      oldSensor: this.data.penSensor
    })
  },
  //回复sensor
  recoverSensor() {
    if (!this.data.penSensor && this.data.penSensor !== 0) {
      this.setData({
        penSensor: this.oldSensor
      })
    }
  },
  //矫正压力值
  correctSensor() {
    if (this.data.penSensor > 4) {
      this.setData({
        penSensor: 4
      })
    }
  },
  // 时间戳转字符串
  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return YY + MM + DD + " " + hh + mm + ss;
  },
  // 改变日期
  changeDate(event) {
    console.log(event.detail)
    this.setData({
      date: event.detail.value
    })
  },
  // 改变时间
  changeTime(event) {
    this.setData({
      time: event.detail.value
    })
  },
  setTime() {
    let time = `${this.data.date} ${this.data.time}:00`
    time = time.replace(/-/g, "/")
    let timeStamp = new Date(time).getTime()
    this.setPenTime(timeStamp)
    Toast.loading({
      message: "正在修改",
      forbidClick: true,
    })
  },
  // getBackPop
  getBackPop() {
    this.setData({
      showPop: false
    })
  }

})